#define _WIN32_DCOM
#include <iostream.h>
#include <stdio.h>
#include <windows.h>
#include <ocidl.h>
#include "component\component.h"

void main()
{
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    if(FAILED(hr))
        cout << "CoInitializeEx failed. " << endl;

    IUnknown* pUnknown;
    hr = CoCreateInstance(CLSID_InsideCOM, NULL, CLSCTX_INPROC_SERVER, 
		IID_IUnknown, (void**)&pUnknown);
    if(FAILED(hr))
		cout << "CoCreateInstance failed. " << endl;

    IPersistStreamInit* pPersistStreamInit;
    hr = pUnknown->QueryInterface(IID_IPersistStreamInit, (void**)&pPersistStreamInit);
    if(FAILED(hr))
        cout << "IID_IPersistStreamInit not supported. " << endl;

	IStream* pStream = 0;
	hr = CreateStreamOnHGlobal(NULL, TRUE, &pStream);
    if(FAILED(hr))
        cout << "CreateStreamOnHGlobal failed. " << endl;

	hr = pPersistStreamInit->InitNew();
    if(FAILED(hr))
		printf("IPersistStreamInit::InitNew failed %0x\n", hr);

	ISum* pSum = 0;
	hr = pUnknown->QueryInterface(IID_ISum, (void**)&pSum);

	int retval = 0;
	hr = pSum->Sum(5, 3, &retval);
	cout << "5 + 3 = " << retval << endl;

	hr = pPersistStreamInit->Save(pStream, FALSE);
	if(FAILED(hr))
		printf("IPersistStreamInit::Save failed %0x\n", hr);

    pPersistStreamInit->Release();
    pUnknown->Release();
	pSum->Release();





	// Create a clone of the object


    LARGE_INTEGER zeroa = { 0, 0 };
    pStream->Seek(zeroa, STREAM_SEEK_SET, NULL);

    hr = CoCreateInstance(CLSID_InsideCOM, NULL, CLSCTX_INPROC_SERVER, 
		IID_IUnknown, (void**)&pUnknown);
    if(FAILED(hr))
		cout << "CoCreateInstance failed. " << endl;

    hr = pUnknown->QueryInterface(IID_IPersistStreamInit, (void**)&pPersistStreamInit);
    if(FAILED(hr))
        cout << "IID_IPersistStreamInit not supported. " << endl;

	hr = pPersistStreamInit->Load(pStream);
    if(FAILED(hr))
       printf("IPersistStreamInit::Load failed %0x\n", hr);

	hr = pUnknown->QueryInterface(IID_ISum, (void**)&pSum);

	hr = pSum->SumPersist(&retval);
	cout << "SumPersist returns " << retval << endl;

	pSum->Release();
	pStream->Release();
    pPersistStreamInit->Release();
    pUnknown->Release();

    CoUninitialize();
}